package com.edu.hbwe.book.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

public class DbUtil {
	
	private static BasicDataSource ds = null;
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
	static {

		Properties properties = new Properties();

		InputStream is = DbUtil.class.getResourceAsStream("/db.properties");

		try {
			properties.load(is);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			ds = BasicDataSourceFactory.createDataSource(properties);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	//提供静态方法得到数据源对象
	public static DataSource getDataSource() {
		return ds;
	}
	
	public static Connection getConnection(){
		Connection conn = tl.get();
		
		try {
			if (conn == null) {
				conn = ds.getConnection();
				tl.set(conn);
			}	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

}
